package com.sport.controller;

import com.google.gson.Gson;
import com.sport.constant.MessageConstant;
import com.sport.constant.WsResultConstant;
import com.sport.context.BaseContext;
import com.sport.mapper.RoomMapper;
import com.sport.pojo.dto.CampMessageDto;
import com.sport.pojo.dto.GameResults;
import com.sport.pojo.dto.RoomDto;
import com.sport.pojo.entity.Room;
import com.sport.pojo.vo.RoomVo;
import com.sport.pojo.entity.UandR;
import com.sport.pojo.entity.User;
import com.sport.pojo.vo.WsResult;
import com.sport.result.Result;

import com.sport.service.RoomService;
import com.sport.websocket.RoomWs;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.sport.constant.MessageConstant.*;

@RestController
@RequestMapping("/user/room")
@Api(tags = "匹配相关接口")
public class RoomController {

    @Autowired
    private RoomService roomService;
    @Autowired
    private RoomWs roomWs;



    @ApiOperation("查询房间状态")
    @GetMapping("/findRoomStatus")
    public  Result findRoomStatus(String roomId){
        return Result.success(new Gson().toJson(roomService.findRoomStatusByRoomId(roomId)));
    }

    @ApiOperation("查询排位模式所有房间")
    @GetMapping("/findRoom")
    public Result findRoom() {
        List<RoomVo> list = roomService.findRoom(BaseContext.getCurrentId());
        Gson gson = new Gson();
        String json = gson.toJson(list);
        return Result.success(json);
    }
    @ApiOperation("查询匹配模式所有房间")
    @GetMapping("/findNormalRoom")
    public Result findNormalRoom() {
        List<RoomVo> list = roomService.findNormalRoom(BaseContext.getCurrentId());
        Gson gson = new Gson();
        String json = gson.toJson(list);
        return Result.success(json);
    }

    @ApiOperation("创建房间")
    @PostMapping("/createroom")
    public Result createRoom(@RequestBody RoomDto roomDto) {
        int info = roomService.createRoom(roomDto);
        if (info != 0) {
            return Result.success(roomDto.getRoomId());
        } else {
            return Result.error(FAILS_CREATEROOM);
        }
    }

    @ApiOperation("用户进入房间")
    @PostMapping("/intoroom")
    public Result uerIntoRoom(@RequestBody UandR uandR) {
        int info = roomService.userIntoRoom(uandR);
        if (info == 1) {
            roomWs.broadcast(uandR.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.ADD_PEOPLE, "新增人员", new Gson().toJson(uandR))));
            return Result.success(String.valueOf(uandR.getCamp()));
        } else if(info == 2) {
            roomWs.broadcast(uandR.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.ROOM_FULL, "房间人满", "房间人满")));
            return Result.success("房间人满",501);
        }else {
            return Result.error(ROOM_INTO_ERROR);
        }
    }
    @ApiOperation("用户更换阵营")
    @PostMapping("/changecamp")
    public Result userChangeCamp(@RequestBody UandR uandR) {

        int info = roomService.userChangeCamp(uandR);

        if (info != 0) {
            roomWs.broadcast(uandR.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.CHANGE_CAMP, "更换阵营", new Gson().toJson(uandR))));
            return Result.success(String.valueOf(uandR.getCamp()));
        } else {
            return Result.error(USER_CHANGERCAMP_ERROR);
        }
    }
    @ApiOperation("裁判开始游戏")
    @PostMapping("/begingame")
    public Result trailBeginGame(String roomId){
        int info = roomService.trailBeginGame(roomId);
        if (info!=0){
            return Result.success();
        }else {
            return Result.error(ROOM_BEGIN_ERROR);
        }
    }
    @ApiOperation("裁判提交结果")
    @PostMapping("/submitresults")
    public Result trailSubmitResults(GameResults gameResults){
        int info = roomService.trailSubmitResults(gameResults);
        if (info!=0){
            return Result.success();
        }else {
            return Result.error(ROOM_SUBMIT_ERROR);
        }
    }
    @ApiOperation("用户退出房间")
    @DeleteMapping("/exitRoom")
    public Result exitRoom(@RequestBody UandR uandR) {
        int info = roomService.exitRoom(uandR);
        if (info != 0) {
            roomWs.broadcast(uandR.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.DELETE_PEOPLE, "退出房间", new Gson().toJson(uandR))));
            return Result.success(String.valueOf(uandR.getCamp()));
        } else {
            return Result.error(ROOM_DELETE_ERROR);
        }
    }

    @ApiOperation("查找房间")
    @GetMapping("/find")
    public Result findRoomByUserId(String userId) {
        RoomVo roomVo = roomService.findRoomByUserId(userId);
        Gson gson = new Gson();
        String s = gson.toJson(roomVo);
        if (roomVo != null) {
            return Result.success(s);
        } else {
            return Result.error(ROOM_NOT_FOUND);
        }
    }

    @ApiOperation("查询房间人员及阵容信息")
    @GetMapping("/findAllNumber")
    public Result fineAllNumber(String roomId) {
        CampMessageDto campMessageDto = roomService.showRoomNumber(roomId);
        Gson gson = new Gson();
        String s = gson.toJson(campMessageDto);
        if (s != null) {
            return Result.success(s);
        } else {
            return Result.error(FIND_ROOMMESSAGE_ERROR);
        }
    }

    @ApiOperation("摧毁房间")
    @DeleteMapping("/destroyRoom")
    public Result destroyRoom(@RequestBody UandR uandR) {
        if (roomService.destroyRoom(uandR) == 1) {
            roomWs.broadcast(uandR.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.DESTROY_ROOM, "房间已解散", new Gson().toJson(uandR))));
            return Result.RoomDestroy(ROOM_DESTROY_SUCCESS, "");
        } else {
            return Result.error(ROOM_DESTROY_ERROR);
        }
    }

    @ApiOperation("房主踢人")
    @DeleteMapping("/kickUser")
    public Result kickUser(@RequestBody UandR uandR){
        if (roomService.kickUser(uandR) !=0) {
            roomWs.broadcastKickUser(uandR.getRoomId(),uandR.getUserId(),BaseContext.getCurrentId(), new Gson().toJson(new WsResult(WsResultConstant.KICK_USER, uandR.getUserName()+"被剔除", new Gson().toJson(uandR))));
            return Result.KillUser("踢出成功", "");
        } else {
            return Result.error("踢出失败");
        }
    }
    @ApiOperation("房主开始")
    @GetMapping("/startGame")
    public Result startGame(String roomId,String place){
       if(roomService.startGame(roomId,place)!=0){
           roomWs.broadcast(roomId,new Gson().toJson(new WsResult(9, "开始游戏", "")));
           return Result.success();
       }else {
           return Result.error("开始失败");
       }

    }
    @ApiOperation("房主结束房间")
    @GetMapping("/endGame")
    public Result endGame(String roomId){
        if(roomService.endGame(roomId)==1){
            return Result.success();
        }else {
            return Result.error("结束失败");
        }
    }
    @ApiOperation("模糊搜索房间")
    @GetMapping("/searchRoom")
    public Result searchRoom(String roomHostName,String type){
        List<RoomVo> list = roomService.searchRoom(roomHostName,type);
        return Result.success(new Gson().toJson(list));
    }
}
